package jwdt.xadmin.flow.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jwdt.xadmin.system.bean.TUser;

import org.snaker.engine.access.Pager;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.HistoryOrder;
import org.snaker.engine.entity.Task;
import org.snaker.engine.entity.WorkItem;
import org.snaker.engine.model.TaskModel.TaskType;

import com.ezerg.util.StringUtil;
import com.ezerg.web.Form;
import com.ezerg.web.Module;
import com.ezerg.web.Page;
import com.ezerg.web.annotation.Controller;
import com.ezerg.web.annotation.RequestMapping;

/**
 * Snaker流程引擎常用Controller
 */
@Controller("/xadmin/flow")
public class TaskAction extends SnakerAction {
	
	@RequestMapping("/taskActive")
	public Page doActive(Form f, Module m) {
		TUser user = (TUser) f.getSession("userInfo");
		List<String> list = new ArrayList<String>();
		list.add(user.getUsername());
		String[] assignees = new String[list.size()];
		list.toArray(assignees);
		
		Pager<WorkItem> majorPage = new Pager<WorkItem>(5);
		Pager<WorkItem> aidantPage = new Pager<WorkItem>(3);
		Pager<HistoryOrder> ccorderPage = new Pager<HistoryOrder>(3);
		List<WorkItem> majorWorks = engine.query()
				.getWorkItems(majorPage, new QueryFilter()
				.setOperators(assignees)
				.setTaskType(TaskType.Major.ordinal()));
		List<WorkItem> aidantWorks = engine.query()
				.getWorkItems(aidantPage, new QueryFilter()
				.setOperators(assignees)
				.setTaskType(TaskType.Aidant.ordinal()));
		List<HistoryOrder> ccWorks = engine.query()
				.getCCWorks(ccorderPage, new QueryFilter()
				.setOperators(assignees)
				.setState(1));
		
		f.add("majorWorks", majorWorks);
		f.add("majorTotal", majorPage.getTotalCount());
		f.add("aidantWorks", aidantWorks);
		f.add("aidantTotal", aidantPage.getTotalCount());
		f.add("ccorderWorks", ccWorks);
		f.add("ccorderTotal", ccorderPage.getTotalCount());
		return m.jspPage(url.concat("activeTask.jsp"));
	}
	
	/**
	 * 根据当前用户查询待办任务列表
	 */
	@RequestMapping("/userTask")
	public Page doUser(Form f, Module m) {
		TUser user = (TUser) f.getSession("userInfo");
		String assignees = user.getUsername();
		Pager<WorkItem> majorPage = new Pager<WorkItem>(5);
		Pager<WorkItem> aidantPage = new Pager<WorkItem>(3);
		Pager<HistoryOrder> ccorderPage = new Pager<HistoryOrder>(3);
		List<WorkItem> majorWorks = engine.query()
				.getWorkItems(majorPage, new QueryFilter()
				.setOperator(assignees)
				.setTaskType(TaskType.Major.ordinal()));
		List<WorkItem> aidantWorks = engine.query()
				.getWorkItems(aidantPage, new QueryFilter()
				.setOperator(assignees)
				.setTaskType(TaskType.Aidant.ordinal()));
		List<HistoryOrder> ccWorks = engine.query()
				.getCCWorks(ccorderPage, new QueryFilter()
				.setOperator(assignees)
				.setState(1));
		
		f.add("majorWorks", majorWorks);
		f.add("majorTotal", majorPage.getTotalCount());
		f.add("aidantWorks", aidantWorks);
		f.add("aidantTotal", aidantPage.getTotalCount());
		f.add("ccorderWorks", ccWorks);
		f.add("ccorderTotal", ccorderPage.getTotalCount());
		return m.jspPage(url.concat("userTask.jsp"));
	}

	@RequestMapping("/taskAddActor")
    public Page doAddActor(Form f, Module m) {
		return m.jspPage(url.concat("actor.jsp"));
    }

	@RequestMapping("/taskDoAddActor")
    public Page doDoAddActor(Form f, Module m) {
        List<Task> tasks = engine.query()
        		.getActiveTasks(new QueryFilter().setOrderId(f.getString(PARA_ORDERID)));
        for(Task task : tasks) {
            if(task.getTaskName().equalsIgnoreCase(f.getString(PARA_TASKNAME)) 
            		&& !StringUtil.nullOrBlank(f.getString("operator"))) {
                engine.task().addTaskActor(task.getId(), f.getString("operator"));
            }
        }
        return m.jsonPage("success");
    }

	//snaker.designer.js r173
	@RequestMapping("/taskTip")
    public Page doTip(Form f, Module m) {
        List<Task> tasks = engine.query()
        		.getActiveTasks(new QueryFilter().setOrderId(f.getString(PARA_ORDERID)));
        StringBuilder builder = new StringBuilder();
        String createTime = "";
        for(Task task : tasks) {
            if(task.getTaskName().equalsIgnoreCase(f.getString(PARA_TASKNAME))) {
                String[] actors = engine.query().getTaskActorsByTaskId(task.getId());
                for(String actor : actors) {
                    builder.append(actor).append(",");
                }
                createTime = task.getCreateTime();
            }
        }
        if(builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("actors", builder.toString());
        data.put("createTime", createTime);
        return m.jsonPage(data);
    }
	
	/**
	 * 活动任务查询列表
	 */
	@RequestMapping("/taskActiveMore")
	public Page doActiveMore(Form f, Module m) {
		TUser user = (TUser) f.getSession("userInfo");
		Pager<WorkItem> page = new Pager<WorkItem>();
		page.setPageNo(f.getInt("pageNo", 1));
		List<String> list = new ArrayList<String>();
		list.add(user.getUsername());
		//log.info(list.toString());
		String[] assignees = new String[list.size()];
		list.toArray(assignees);
		int taskType = f.getInt("taskType");
		engine.query().getWorkItems(page, 
				new QueryFilter().setOperators(assignees).setTaskType(taskType));
		f.add("page", page);
		f.add("taskType", taskType);
		return m.jspPage(url.concat("activeTaskMore.jsp"));
	}
	
	/**
	 * 活动任务查询列表
	 */
	@RequestMapping("/taskActiveCCMore")
	public Page doActiveCCMore(Form f, Module m) {
		TUser user = (TUser) f.getSession("userInfo");
		Pager<HistoryOrder> page = new Pager<HistoryOrder>();
		page.setPageNo(f.getInt("pageNo", 1));
		List<String> list = new ArrayList<String>();
		list.add(user.getUsername());
		//log.info(list.toString());
		String[] assignees = new String[list.size()];
		list.toArray(assignees);
		engine.query()
				.getCCWorks(page, new QueryFilter()
				.setOperators(assignees)
				.setState(1));
		f.add("page", page);
		return m.jspPage(url.concat("activeCCMore.jsp"));
	}
	
	/**
	 * 测试任务的执行
	 * @param model
	 * @return
	 */
	@RequestMapping("/taskExec")
	public Page doExec(Form f, Module m) {
		TUser user = (TUser) f.getSession("userInfo");
		execute(f.getString(PARA_TASKID), user.getUsername(), null);
		return m.getRedirectPage(url +("taskActive.do"));
	}
	
	/**
	 * 活动任务的驳回
	 * @param model
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/taskReject")
	public Page doReject(Form f, Module m) {
		TUser user = (TUser) f.getSession("userInfo");
		String error = "";
		try {
			executeAndJump(f.getString(PARA_TASKID), user.getUsername(), null, null);
		} catch(Exception e) {
			error = "?error=1";
		}
		return m.getRedirectPage(url +("taskActive.do" + error));
	}
	
	/**
	 * 历史完成任务查询列表
	 * @return
	 */
	@RequestMapping("/taskHistory")
	public Page doHistory(Form f, Module m) {
		TUser user = (TUser) f.getSession("userInfo");
		Pager<WorkItem> page = new Pager<WorkItem>();
		page.setPageNo(f.getInt("pageNo", 1));
		engine.query().getHistoryWorkItems(page, 
				new QueryFilter().setOperator(user.getUsername()));
		f.add("page", page);
		return m.jspPage(url.concat("historyTask.jsp"));
	}
	
	/**
	 * 历史任务撤回
	 */
	@RequestMapping("/taskUndo")
	public Page doUndo(Form f, Module m) {
		TUser user = (TUser) f.getSession("userInfo");
		String returnMessage = "";
		try {
			engine.task().withdrawTask(f.getString(PARA_TASKID), user.getUsername());
			returnMessage = "任务撤回成功.";
		} catch(Exception e) {
			returnMessage = e.getMessage();
		}
		f.add("returnMessage", returnMessage);
		return m.getRedirectPage(url +("taskHistory.do"));
	}
}
